
#import "RNReactNativeMfbbShare.h"

#import <UMCommon/MobClick.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>

@implementation RNReactNativeMfbbShare

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_MODULE()


#pragma mark SDK 初始化
+ (RNReactNativeMfbbShare *)sharedInstance
{
    static RNReactNativeMfbbShare * sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[RNReactNativeMfbbShare alloc]init];
    });
    
    return sharedInstance;
}

- (void)initSDKWithParams:(NSDictionary *)dict launchOptions:(NSDictionary *)launchOptions{
    
    NSString * umAppkey = [NSString stringWithFormat:@"%@",[dict valueForKey:@"UMENG_APP_KEY"]];
    [UMConfigure initWithAppkey:umAppkey channel:@"App Store"];
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
    //微信平台分享
    NSString * weixinAppkey = [dict valueForKey:@"WEIXIN_APP_ID"];
    NSString * weixinAppSecret = [dict valueForKey:@"WEIXIN_APP_SECRECT"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:weixinAppkey appSecret:weixinAppSecret redirectURL:nil];
    
    //微信朋友圈
    NSString * weixinAppkey = [dict valueForKey:@"WEIXIN_APP_ID"];
    NSString * weixinAppSecret = [dict valueForKey:@"WEIXIN_APP_SECRECT"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:weixinAppkey appSecret:weixinAppSecret redirectURL:nil];
    
    // QQ
    NSString * qqAppKey = [dict valueForKey:@"QQ_APP_ID"];
    NSString * qqAppSecret = [dict valueForKey:@"QQ_APP_SECRECT"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:qqAppKey appSecret:qqAppSecret redirectURL:nil];
    
    // QQ空间
    NSString * qqAppKey = [dict valueForKey:@"QQ_APP_ID"];
    NSString * qqAppSecret = [dict valueForKey:@"QQ_APP_SECRECT"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:qqAppKey appSecret:qqAppSecret redirectURL:nil];
    

    
}

#pragma mark  统计模块
RCT_EXPORT_METHOD(onPageStart:(NSString *)pageName)
{
    if (pageName == nil || [pageName isKindOfClass:[NSNull class]]) {
        return;
    }
    [MobClick beginLogPageView:pageName];
}

RCT_EXPORT_METHOD(onPageEnd:(NSString *)pageName)
{
    if (pageName == nil || [pageName isKindOfClass:[NSNull class]]) {
        return;
    }
    [MobClick endLogPageView:pageName];
}

RCT_EXPORT_METHOD(onEvent:(NSString *)eventId)
{
    if (eventId == nil || [eventId isKindOfClass:[NSNull class]]) {
        return;
    }
    [MobClick event:eventId];
}
RCT_EXPORT_METHOD(onEventWithLable:(NSString *)eventId eventLabel:(NSString *)eventLabel)
{
    if (eventId == nil || [eventId isKindOfClass:[NSNull class]]) {
        return;
    }
    if ([eventLabel isKindOfClass:[NSNull class]]) {
        eventLabel = nil;
    }
    [MobClick event:eventId label:eventLabel];
    
}


RCT_EXPORT_METHOD(onEventWithMap:(NSString *)eventId parameters:(NSDictionary *)parameters)
{
    if (eventId == nil || [eventId isKindOfClass:[NSNull class]]) {
        return;
    }
    if (parameters == nil && [parameters isKindOfClass:[NSNull class]]) {
        parameters = nil;
    }
    [MobClick event:eventId attributes:parameters];
}

RCT_EXPORT_METHOD(onEventWithMapAndCount:(NSString *)eventId parameters:(NSDictionary *)parameters eventNum:(int)eventNum)
{
    if (eventId == nil || [eventId isKindOfClass:[NSNull class]]) {
        return;
    }
    if (parameters == nil && [parameters isKindOfClass:[NSNull class]]) {
        parameters = nil;
    }
    
    [MobClick event:eventId attributes:parameters counter:eventNum];
}

RCT_EXPORT_METHOD(onEventObject:(NSString *)eventId parameters:(NSDictionary *)parameters)
{
    if (eventId == nil || [eventId isKindOfClass:[NSNull class]]) {
        return;
    }
    if (parameters == nil && [parameters isKindOfClass:[NSNull class]]) {
        parameters = nil;
    }
    [MobClick event:eventId attributes:parameters];
}






#pragma mark 分享登录模块



- (BOOL)handleUrl:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    
    return [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    
}


- (UMSocialPlatformType)platformType:(NSInteger)platform
{
  switch (platform) {
    case 0: // QQ
      return UMSocialPlatformType_QQ;
    case 1: // Sina
      return UMSocialPlatformType_Sina;
    case 2: // wechat
      return UMSocialPlatformType_WechatSession;
    case 3:
      return UMSocialPlatformType_WechatTimeLine;
    case 4:
      return UMSocialPlatformType_Qzone;
    case 5:
      return UMSocialPlatformType_Email;
    case 6:
      return UMSocialPlatformType_Sms;
    case 7:
      return UMSocialPlatformType_Facebook;
    case 8:
      return UMSocialPlatformType_Twitter;
    case 9:
      return UMSocialPlatformType_WechatFavorite;
    case 10:
      return UMSocialPlatformType_GooglePlus;
    case 11:
      return UMSocialPlatformType_Renren;
    case 12:
      return UMSocialPlatformType_TencentWb;
    case 13:
      return UMSocialPlatformType_Douban;
    case 14:
      return UMSocialPlatformType_FaceBookMessenger;
    case 15:
      return UMSocialPlatformType_YixinSession;
    case 16:
      return UMSocialPlatformType_YixinTimeLine;
    case 17:
      return UMSocialPlatformType_Instagram;
    case 18:
      return UMSocialPlatformType_Pinterest;
    case 19:
      return UMSocialPlatformType_EverNote;
    case 20:
      return UMSocialPlatformType_Pocket;
    case 21:
      return UMSocialPlatformType_Linkedin;
    case 22:
      return UMSocialPlatformType_UnKnown; // foursquare on android
    case 23:
      return UMSocialPlatformType_YouDaoNote;
    case 24:
      return UMSocialPlatformType_Whatsapp;
    case 25:
      return UMSocialPlatformType_Line;
    case 26:
      return UMSocialPlatformType_Flickr;
    case 27:
      return UMSocialPlatformType_Tumblr;
    case 28:
      return UMSocialPlatformType_APSession;
    case 29:
      return UMSocialPlatformType_KakaoTalk;
    case 30:
      return UMSocialPlatformType_DropBox;
    case 31:
      return UMSocialPlatformType_VKontakte;
    case 32:
      return UMSocialPlatformType_DingDing;
    case 33:
      return UMSocialPlatformType_UnKnown; // more
    default:
      return UMSocialPlatformType_QQ;
  }
}

- (void)shareWithText:(NSString *)text icon:(NSString *)icon link:(NSString *)link title:(NSString *)title platform:(NSInteger)platform completion:(UMSocialRequestCompletionHandler)completion
{
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    if (link.length > 0) {
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:text thumImage:icon];
        shareObject.webpageUrl = link;
        
        messageObject.shareObject = shareObject;
    } else if (icon.length > 0) {
        id img = nil;
        if ([icon hasPrefix:@"http"]) {
            img = icon;
        } else {
            if ([icon hasPrefix:@"/"]) {
                img = [UIImage imageWithContentsOfFile:icon];
            } else {
                img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:icon ofType:nil]];
            }
        }
        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
        shareObject.thumbImage = img;
        shareObject.shareImage = img;
        messageObject.shareObject = shareObject;
        
        messageObject.text = text;
    } else if (text.length > 0) {
        messageObject.text = text;
    } else {
        if (completion) {
            completion(nil, [NSError errorWithDomain:@"UShare" code:-3 userInfo:@{@"message": @"invalid parameter"}]);
            return;
        }
    }
    
    [[UMSocialManager defaultManager] shareToPlatform:platform messageObject:messageObject currentViewController:nil completion:completion];
    
}
//压缩图片到固定大小
- (NSData *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return data;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return data;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return data;
}

/*
 ****微信小程序分享
 platformType:平台，目前暂时只传微信UMSocialPlatformType_WechatSession=1
 title：小程序标题
 desc：小程序描述
 thumimageUrl;小程序缩略图
 webpageUrl:低版本小程序跳转H5链接
 user_name;@"小程序username，如 gh_3ac2059ac66f";
 path： @"小程序页面路径，如 pages/page10007/page10007";
 type： UShareWXMiniProgramTypeRelease = 0,   正式版
      UShareWXMiniProgramTypeTest = 1,   发版
      UShareWXMiniProgramTypePreview = 2, 体验版
 */

RCT_EXPORT_METHOD(shareMiniProgramToPlatformType:(NSInteger)platformType  title:(NSString *)title desc:(NSString *)desc thumImage:(NSString *)thumimageUrl  webpageUrl:(NSString *)webpageUrl  user_name:(NSString *)user_name  miniProgramPath:(NSString *)path  MiniProgramType:(NSInteger)type completion:(RCTResponseSenderBlock)completion)
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    UMShareMiniProgramObject *shareObject = [UMShareMiniProgramObject shareObjectWithTitle:title descr:desc thumImage:thumimageUrl];
    shareObject.webpageUrl = webpageUrl;
    shareObject.userName = user_name;
    shareObject.path = path;
    messageObject.shareObject = shareObject;
    
    //小程序使用本地图片分享区别处理
    id img = nil;
    if ([thumimageUrl hasPrefix:@"http"]) {
        NSData * thumData = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumimageUrl]];
        img = [UIImage imageWithData:thumData];
    } else {
        if ([thumimageUrl hasPrefix:@"/"]) {
            img = [UIImage imageWithContentsOfFile:thumimageUrl];
        } else {
            img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:thumimageUrl ofType:nil]];
        }
    }
    NSData * resultData = [self compressImage:img toByte:128*1024];
    shareObject.hdImageData = resultData;
    shareObject.miniProgramType = type; // 可选体验版和开发板
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
        if (completion) {
            if (error) {
                NSString *msg = error.userInfo[@"NSLocalizedFailureReason"];
                if (!msg) {
                    msg = error.userInfo[@"message"];
                }if (!msg) {
                    msg = @"share failed";
                }
                NSInteger stcode =error.code;
                if(stcode == 2009){
                    stcode = -1;
                }
                completion(@[@(stcode), msg]);
            } else {
                completion(@[@200, @"share success"]);
            }
        }
    }];
}


/** ios  调用系统分享多张图片功能，可以分享到微信好友，QQ好友，QQ朋友圈，但分享不到微信朋友圈*/
RCT_EXPORT_METHOD(shareForIosSystemWithImageUrl:(NSArray *)urlArray completion:(RCTResponseSenderBlock)completion){
    
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for (int i = 0; i <8 && i<urlArray.count; i++) {
        if ([urlArray[i] isKindOfClass:[NSString class]]) {
            NSString *URL = urlArray[i];
            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
            UIImage *imagerang = [UIImage imageWithData:data];
            
            NSString *path_sandox = NSHomeDirectory();
            NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/ShareWX%d.jpg",i]];
            [UIImagePNGRepresentation(imagerang) writeToFile:imagePath atomically:YES];
            
            NSURL *shareobj = [NSURL fileURLWithPath:imagePath];
            
            /** 这里做个解释 imagerang : UIimage 对象  shareobj:NSURL 对象 这个方法的实际作用就是 在调起微信的分享的时候 传递给他 UIimage对象,在分享的时候 实际传递的是 NSURL对象 达到我们分享九宫格的目的 */
            
            SharedItem *item = [[SharedItem alloc] initWithData:imagerang andFile:shareobj];
            
            [array addObject:item];
        }
        
    }
    
    UIActivityViewController *activityViewController =[[UIActivityViewController alloc] initWithActivityItems:array
                                                                                        applicationActivities:nil];
    UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
        NSLog(@"%@",activityType);
        if (completion) {
            if (activityError) {
                NSString *msg = activityError.userInfo[@"NSLocalizedFailureReason"];
                if (!msg) {
                    msg = activityError.userInfo[@"message"];
                }if (!msg) {
                    msg = @"share failed";
                }
                NSInteger stcode =activityError.code;
                if(stcode == 2009){
                    stcode = -1;
                }
                completion(@[@(stcode), msg]);
            } else {
                completion(@[@200, @"share success"]);
            }
        }
        [activityViewController dismissViewControllerAnimated:YES completion:nil];
    };
    activityViewController.completionWithItemsHandler = myBlock;
    if (activityViewController) {
        [[CoordinatingController sharedInstance] presentViewController:activityViewController animated:YES completion:^{
            
        }];
        
    }
}


RCT_EXPORT_METHOD(share:(NSString *)text icon:(NSString *)icon link:(NSString *)link title:(NSString *)title platform:(NSInteger)platform completion:(RCTResponseSenderBlock)completion)
{
    UMSocialPlatformType plf = [self platformType:platform];
    if (plf == UMSocialPlatformType_UnKnown) {
        if (completion) {
            completion(@[@(UMSocialPlatformType_UnKnown), @"invalid platform"]);
            return;
        }
    }
    
    [self shareWithText:text icon:icon link:link title:title platform:plf completion:^(id result, NSError *error) {
        if (completion) {
            if (error) {
                NSString *msg = error.userInfo[@"NSLocalizedFailureReason"];
                if (!msg) {
                    msg = error.userInfo[@"message"];
                }if (!msg) {
                    msg = @"share failed";
                }
                NSInteger stcode =error.code;
                if(stcode == 2009){
                    stcode = -1;
                }
                completion(@[@(stcode), msg]);
            } else {
                completion(@[@200, @"share success"]);
            }
        }
    }];
    
}

RCT_EXPORT_METHOD(shareboard:(NSString *)text icon:(NSString *)icon link:(NSString *)link title:(NSString *)title platform:(NSArray *)platforms completion:(RCTResponseSenderBlock)completion)
{
    NSMutableArray *plfs = [NSMutableArray array];
    for (NSNumber *plf in platforms) {
        [plfs addObject:@([self platformType:plf.integerValue])];
    }
    if (plfs.count > 0) {
        [UMSocialUIManager setPreDefinePlatforms:plfs];
    }
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        [self shareWithText:text icon:icon link:link title:title platform:platformType completion:^(id result, NSError *error) {
            if (completion) {
                if (error) {
                    NSString *msg = error.userInfo[@"NSLocalizedFailureReason"];
                    if (!msg) {
                        msg = error.userInfo[@"message"];
                    }if (!msg) {
                        msg = @"share failed";
                    }
                    NSInteger stcode =error.code;
                    if(stcode == 2009){
                        stcode = -1;
                    }
                    completion(@[@(stcode), msg]);
                } else {
                    completion(@[@200, @"share success"]);
                }
            }
        }];
    }];
}


RCT_EXPORT_METHOD(auth:(NSInteger)platform completion:(RCTResponseSenderBlock)completion)
{
    UMSocialPlatformType plf = [self platformType:platform];
    if (plf == UMSocialPlatformType_UnKnown) {
        if (completion) {
            completion(@[@(UMSocialPlatformType_UnKnown), @"invalid platform"]);
            return;
        }
    }
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:plf currentViewController:nil completion:^(id result, NSError *error) {
        if (completion) {
            if (error) {
                NSString *msg = error.userInfo[@"NSLocalizedFailureReason"];
                if (!msg) {
                    msg = error.userInfo[@"message"];
                }if (!msg) {
                    msg = @"share failed";
                }
                NSInteger stCode = error.code;
                if(stCode == 2009){
                    stCode = -1;
                }
                completion(@[@(stCode), @{}, msg]);
            } else {
                UMSocialUserInfoResponse *authInfo = result;
                
                NSMutableDictionary *retDict = [NSMutableDictionary dictionaryWithCapacity:8];
                retDict[@"uid"] = authInfo.uid;
                retDict[@"openid"] = authInfo.openid;
                retDict[@"unionid"] = authInfo.unionId;
                retDict[@"accessToken"] = authInfo.accessToken;
                retDict[@"refreshToken"] = authInfo.refreshToken;
                retDict[@"expiration"] = authInfo.expiration;
                
                retDict[@"name"] = authInfo.name;
                retDict[@"profile_image_url"] = authInfo.iconurl;
                retDict[@"gender"] = authInfo.unionGender;
                
                NSDictionary *originInfo = authInfo.originalResponse;
                retDict[@"city"] = originInfo[@"city"];
                retDict[@"province"] = originInfo[@"province"];
                retDict[@"country"] = originInfo[@"country"];
                
                completion(@[@0, retDict, @""]);
            }
        }
    }];
    
}

RCT_EXPORT_METHOD(isInstall:(NSString *)platform callBack:(RCTResponseSenderBlock)callback){
    
    //检测微信是否安装
    if ([platform isEqualToString:@"1"]) {
        BOOL isInstall =  [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatSession];
        callback(@[@"1",@(isInstall)]);
    }else if ([platform isEqualToString:@"2"]){
        //        检测QQ是否安装
        BOOL isInstall =  [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ];
        callback(@[@"2",@(isInstall)]);
    }
}

//自定义平台在1000-2000之间
RCT_EXPORT_METHOD(addCustomPlatformWithoutFilted:(NSInteger)platform withPlatformIcon:(NSString*)platformIconName
                  withPlatformName:(NSString*)platformName) {
    
    [UMSocialUIManager addCustomPlatformWithoutFilted:platform withPlatformIcon:[UIImage imageNamed:platformIconName] withPlatformName:platformName];
}


@end

